﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using ESoft.DataAccess.Models;
using ESoft.Exceptions;
using ESoft.Extensions;
using ESoft.Helpers;
using Microsoft.EntityFrameworkCore;

namespace ESoft.DataAccess.EfCore
{
    /// <summary>
    /// 
    /// </summary>
    public class BaseRepositry : IBaseReponsitory
    {
        protected readonly DataContext Db;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="db"></param>
        public BaseRepositry(DataContext db)
        {
            this.Db = db;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public virtual T Find<T>(object id) where T : EntityBase
        {
            return Db.Set<T>().Find(id);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public virtual async Task<T> FindAsync<T>(object id) where T : EntityBase
        {
            return await Db.Set<T>().FindAsync(id);
        }

        public virtual T First<T>(Expression<Func<T, bool>> predicate) where T : EntityBase
        {
            if (predicate != null)
                return Db.Set<T>().FirstOrDefault(predicate);
            else
                return Db.Set<T>().FirstOrDefault();
        }

        public virtual async Task<T> FirstOrDefaultAsync<T>(Expression<Func<T, bool>> predicate) where T : EntityBase
        {
            if (predicate != null)
                return await Db.Set<T>().FirstOrDefaultAsync(predicate);
            else
                return await Db.Set<T>().FirstOrDefaultAsync();
        }

        public virtual T Add<T>(T entity) where T : EntityBase
        {
            var memberInfo = entity.GetType().GetProperties().FirstOrDefault(x => x.GetCustomAttributes(typeof(KeyAttribute), false).Any());

            if (memberInfo != null && ((string)memberInfo.GetValue(entity)).IsNullOrWhiteSpace()) entity.SetModelValue(memberInfo, StringHelper.GetId());

            Db.Set<T>().Add(entity);
            Db.SaveChanges();
            return entity;
        }

        public virtual async Task<T> AddAsync<T>(T entity) where T : EntityBase
        {
            var memberInfo = entity.GetType().GetProperties().FirstOrDefault(x => x.GetCustomAttributes(typeof(KeyAttribute), false).Any());

            if (memberInfo != null)
            {
                var key = memberInfo.GetValue(entity) as string;
                if (key.IsNullOrWhiteSpace()) entity.SetModelValue(memberInfo, StringHelper.GetId());
            }

            Db.Set<T>().Add(entity);
            await Db.SaveChangesAsync();
            return entity;
        }

        public virtual bool Update<T>(T entity) where T : EntityBase
        {
            Db.Entry(entity).State = EntityState.Modified;
            Db.SaveChanges();
            return true;
        }

        public virtual async Task<T> UpdateAsync<T>(T entity) where T : EntityBase
        {
            var memberInfo = entity.GetType().GetProperties().FirstOrDefault(x => x.GetCustomAttributes(typeof(KeyAttribute), false).Any());
            if (memberInfo == null)
            {
                throw new AppException(GetType().ToString(), "找不到对应标识！");
            }
            Db.Set<T>().Update(entity);
            await Db.SaveChangesAsync();
            return entity;
        }

        public virtual bool UpdateBatch<T>(List<T> entitys) where T : EntityBase
        {
            foreach (var entity in entitys)
            {
                Db.Entry(entity).State = EntityState.Modified;
            }
            Db.SaveChanges();
            return true;
        }

        /// <summary>
        /// 异步批量更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public virtual async Task UpdateBatchAsync<T>(List<T> entitys) where T : EntityBase
        {
            foreach (var entity in entitys)
            {
                var memberInfo = entity.GetType().GetProperties().FirstOrDefault(x => x.GetCustomAttributes(typeof(KeyAttribute), false).Any());
                if (memberInfo == null)
                {
                    throw new AppException(GetType().ToString(), "找不到对应标识！");
                }
                Db.Set<T>().Update(entity);
            }

            await Db.SaveChangesAsync();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete<T>(object id) where T : EntityBase
        {
            return Delete(Find<T>(id));
        }

        /// <summary>
        /// 根据ID删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync<T>(object id) where T : EntityBase
        {
            return await DeleteAsync(await FindAsync<T>(id));
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync<T>(T entity) where T : EntityBase
        {
            Db.Entry(entity).State = EntityState.Deleted;
            await Db.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual bool Delete<T>(T entity) where T : EntityBase
        {
            Db.Entry(entity).State = EntityState.Deleted;
            Db.SaveChanges();
            return true;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entities"></param>
        /// <returns></returns>
        public virtual bool DeleteBatch<T>(IEnumerable<T> entities) where T : EntityBase
        {
            foreach (var entity in entities) Delete(entity);
            return true;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entities"></param>
        /// <returns></returns>
        public virtual async Task<bool> DeleteBatchAsync<T>(IEnumerable<T> entities) where T : EntityBase
        {
            foreach (var entity in entities)
                await DeleteAsync(entity);
            return true;
        }

        /// <summary>
        /// 检查是否存在
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public virtual bool Exist<T>(Expression<Func<T, bool>> predicate) where T : EntityBase
        {
            return Db.Set<T>().Any(predicate);
        }

        /// <summary>
        /// 获取总行数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public virtual int Count<T>(Expression<Func<T, bool>> predicate) where T : EntityBase
        {
            return Db.Set<T>().Count(predicate);
        }

        /// <summary>
        /// 获取总行数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public virtual async Task<int> CountAsync<T>(Expression<Func<T, bool>> predicate) where T : EntityBase
        {
            if (predicate == null)
                return await Db.Set<T>().CountAsync();

            return await Db.Set<T>().CountAsync(predicate);
        }

        /// <summary>
        /// 获取总数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <param name="selector"></param>
        /// <returns></returns>
        public virtual int Sum<T>(Expression<Func<T, bool>> predicate, Expression<Func<T, int>> selector) where T : EntityBase
        {
            try
            {
                if (predicate == null) return Db.Set<T>().Sum(selector);
                return Db.Set<T>().Where(predicate).Sum(selector);
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 总数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <param name="selector"></param>
        /// <returns></returns>
        public virtual async Task<int> SumAsync<T>(Expression<Func<T, bool>> predicate, Expression<Func<T, int>> selector) where T : EntityBase
        {
            try
            {
                if (predicate == null) return await Db.Set<T>().SumAsync(selector);
                return await Db.Set<T>().Where(predicate).SumAsync(selector);
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 总数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <param name="selector"></param>
        /// <returns></returns>
        public virtual decimal Sum<T>(Expression<Func<T, bool>> predicate, Expression<Func<T, decimal>> selector) where T : EntityBase
        {
            try
            {
                if (predicate == null) return Db.Set<T>().Sum(selector);
                return Db.Set<T>().Where(predicate).Sum(selector);
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 获取全部
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public virtual async Task<List<T>> FindAllAsync<T>() where T : EntityBase
        {
            return await Db.Set<T>().ToListAsync();
        }

        /// <summary>
        /// 获取全部
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public virtual IEnumerable<T> FindAll<T>() where T : EntityBase
        {
            return Db.Set<T>().ToList();
        }

        /// <summary>
        /// 获取全部
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public virtual List<T> FindEntities<T>(Expression<Func<T, bool>> predicate) where T : EntityBase
        {
            return Db.Set<T>().Where(predicate).ToList();
        }

        /// <summary>
        /// 获取全部
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public virtual async Task<List<T>> FindEntitiesAsync<T>(Expression<Func<T, bool>> predicate) where T : EntityBase
        {
            return await Db.Set<T>().Where(predicate).ToListAsync();
        }

        /// <summary>
        /// 分页获取全部
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="page"></param>
        /// <param name="predicate"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public virtual IQueryable<T> FindEntitiesByPage<T>(PageInput page, Expression<Func<T, bool>> predicate, SortVo sort) where T : EntityBase
        {
            var lst = Db.Set<T>().Where(predicate);
            lst = sort.SortWay ? lst.OrderBy(sort.SortField) : lst.OrderByDescending(sort.SortField);

            return lst.Skip(page.Limit * (page.Page - 1))
                .Take(page.Limit);
        }

        /// <summary>
        /// 分页获取全部
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="page"></param>
        /// <param name="predicate"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public async Task<List<T>> FindEntitiesByPageAsync<T>(PageInput page, Expression<Func<T, bool>> predicate, SortVo sort) where T : EntityBase
        {
            var lst = Db.Set<T>().Where(predicate);
            lst = sort.SortWay ? lst.OrderBy(sort.SortField) : lst.OrderByDescending(sort.SortField);

            return await lst.Skip(page.Limit * (page.Page - 1))
                .Take(page.Limit).ToListAsync();
        }
    }
}